package com.example.mrwang.qrimagetool;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.io.UnsupportedEncodingException;


public class QRImageTool {
	
		public static Bitmap getQRCOde(String code,int QR_WIDTH,int QR_HEIGHT) {
			Bitmap bitmap = null;
			try {
				bitmap = create2DCode(code, QR_WIDTH, QR_HEIGHT);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (WriterException e) {
				e.printStackTrace();
			}
			if (bitmap == null) {
				return null;
			}
			Paint paint = new Paint();
			paint.setColor(Color.WHITE);
			paint.setAntiAlias(true);

			Bitmap newb = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Config.ARGB_8888);
			Canvas cv = new Canvas(newb);

			cv.drawColor(Color.WHITE);

			cv.drawBitmap(bitmap, 0, 0, null);
			cv.save(Canvas.ALL_SAVE_FLAG);
			cv.restore();//
			return newb;

		}

		private static Bitmap create2DCode(String code, int QR_WIDTH, int QR_HEIGHT) throws UnsupportedEncodingException,
				WriterException {
			BitMatrix matrix = new MultiFormatWriter().encode(code,
					BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT);
			int width = matrix.getWidth();
			int height = matrix.getHeight();
			int[] pixels = new int[width * height];
			for (int y = 0; y < height; y++) {
				for (int x = 0; x < width; x++) {
					if (matrix.get(x, y)) {
						pixels[y * width + x] = 0xff000000;
					}
				}
			}
			Bitmap bitmap = Bitmap.createBitmap(width, height,
					Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
			return bitmap;
		}
}
